import { _decorator, Component, find, instantiate, Node, NodePool, Prefab, resources } from 'cc';
import { Dictionary } from '../utils/Dictionary';
import { LayerBase } from './LayerBase';
const { ccclass, property } = _decorator;

@ccclass('UILayerMgr')
export class UILayerMgr {
    
    private static ins: UILayerMgr = null;

    nodePools: NodePool[] = [];
    existLayerDic: Dictionary<string, Node> = new Dictionary();//正在显示的layer
    isInitAlready = false;//是否ui层初始化成功

    static get getIns() {
        if (!this.ins) {
            this.ins = new UILayerMgr();
        }
        return this.ins;
    }

    // protected onLoad(): void {
    //     this.ins = this;

    //     //预创建需要用到的layer
    //     this.ins.initLayerPrePool()
    // }

    // protected start(): void {
    //     this.layerParentRoot=find("Canvas/uiLayerRoot");
    // }
 
    //创建ui窗口预制体
    openUILayer(preName,somedData=null) {
        if (this.existLayerDic.containsKey(preName)==false) {//如果窗口已经打开了，就不再打开
                let uiPre = this.nodePools[`${preName}`].get();
                if (uiPre) {
                    uiPre.setParent(find("Canvas/uiLayerRoot"));
                    uiPre.setPosition(0, 0, 0);
                    uiPre.getComponent(LayerBase).init(somedData);
                    this.existLayerDic.set(preName,uiPre);
                }
        }
        else{
            console.log("窗口已经存在")
            return;
        }
            
    }
    //创建ui窗口预制体
    closeUILayer(preName) {
        if (this.existLayerDic.containsKey(preName)) {
            this.nodePools[`${preName}`].put(this.existLayerDic.get(`${preName}`));
            this.existLayerDic.delete(preName);
        }
    }

    closeAllLayer() {
        this.existLayerDic.getKeyList().forEach((ele) => {
            this.nodePools[`${ele}`].put(this.existLayerDic.get(`${ele}`));
        })
        this.existLayerDic=new Dictionary();
    }

    resfreshUI(preName, somedData = null) {
        if (this.existLayerDic.containsKey(preName)) {
            this.existLayerDic.get(preName).getComponent(LayerBase).init(somedData);
        }
    }

    initAllPool(poolName, prefab, count) {
        if (!this.nodePools[`${poolName}`]) {
            this.nodePools[`${poolName}`] = new NodePool();

                for (let i = 0; i < count; i++) {
                    let pre=instantiate(prefab);
                    this.nodePools[`${poolName}`].put(pre)
                }
        }

    }

    initLayerPrePool() {
        new Promise((resolve, reject) => {
            resources.loadDir("prefabs/layerPrefab", (err, res) => {
                for (const key in res) {
                    this.initAllPool(res[key].name, res[key], 1)
                }
                resolve(true)
            })
        }).then(() => { this.isInitAlready = true }).catch((err) => { console.log(err) })
    }

}


